package com.m.man.util;

import org.springframework.util.DigestUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Md5AndShaUtil {

    /**
     * 生成  sha 值
     */
    public static String getSHAofFile(String path){
        MessageDigest digest = null;
        FileInputStream in = null;
        byte buffer [] = new byte[8192];
        int len;
        try {
            digest = MessageDigest.getInstance("SHA-1");
            in = new FileInputStream(new File(path));
            while( (len = in.read(buffer)) != -1){
                digest.update(buffer,0,len);
            }
            BigInteger bigInt = new BigInteger(1,digest.digest());
            return bigInt.toString(16);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }finally{
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }
    }

    /**
     * 生成 文件 的 md5  值
     */
    public static String getMD5ofFile(String path){
        MessageDigest digest = null;
        FileInputStream in = null;
        byte buffer [] = new byte[8192];
        int len;
        try {
            digest = MessageDigest.getInstance("MD5");
            in = new FileInputStream(new File(path));
            while( (len = in.read(buffer)) != -1){
                digest.update(buffer,0,len);
            }
            BigInteger bigInt = new BigInteger(1,digest.digest());
            return bigInt.toString(16);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }finally{
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }
    }
    /**
     * 生成 文件 的 md5  值    也是分多次读入文件
     */
    public static String getMD5ofFileSimple(String path){
        try {
             return DigestUtils.md5DigestAsHex(new FileInputStream(path));
            //import org.apache.commons.codec.digest.DigestUtils;
//            return DigestUtils.md5Hex(new FileInputStream(path));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
    }
}
